package com.itheima.stargraph.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedissionConfig {

    /**
     * 获取redisson的客户端对象
     * @param redisProperties
     * @return
     */
    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties){
        //设置Redisson的配置类
        Config config = new Config();
        //指定使用单个redis服务器;  设置地址;   动态填充
        config.useSingleServer().setAddress(String.format("redis://%s:%s",redisProperties.getHost(),redisProperties.getPort()));

        //返回Redisson的实例
        return Redisson.create(config);
    }

    /**
     * 获取StringRedisTemplate的bean对象
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisProperties redisProperties){
        //创建LettuceConnectionFactory对象,与redis服务器建立连接
        //LettuceConnectionFactory是基于Netty的异步Redis客户端,性能高
        LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisProperties.getHost(),redisProperties.getPort());

        //启动LettuceConnectionFactory,初始化连接
        lettuceConnectionFactory.start();

        //使用配置好的LettuceConnectionFactory创建并返回一个StringRedisTemplate实例
        return new StringRedisTemplate(lettuceConnectionFactory);
    }

}